<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2019/2/20
 * Time: 10:51
 */

namespace app\api\controller\v8;

use app\api\controller\v2\Auth;
use app\common\model\AstroSettingUser;

/**
 * 星盘配置相关接口
 * Class Astroset
 * @package app\api\controller\v8
 */
class Astroset extends Auth
{
    /**
     * 获取星盘配置
     * @method GET
     * @return \think\response\Json
     */
    public function index()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $param = request()->only(['tid', 'chart']);

        $validate = validate('Astroset');

        if (!$validate->scene('index')->check($param))
        {
            return show(config('code.error'), (string)$validate->getError());
        }

        $map = ['uid' => $this->user['id'], 'chart' => $param['chart'], 'tid' => $param['tid']];

        $AstroSettingUserModel = new AstroSettingUser();

        $data = $AstroSettingUserModel->getUserSettingByTid($map);

        if (isset($data['planet']) && $data['planet'])
        {
            $data = ChangeSettingFormat($data);
        }

        return show(config('code.success'), '加载成功', $data);
    }

    /**
     * 更新星盘配置
     * @method POST
     * @return \think\response\Json
     */
    public function update()
    {
        if (!request()->isPost())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $param = request()->param();

        $decodeValue = json_decode($param['chart_value'], true);

        if ($param['chart'] === 'firdaria' && !isset($decodeValue['firdaria']))
        {
            $decodeValue['firdaria'] = 'default';
        }

        $param['chart_value'] = json_encode($decodeValue, true);

        $validate = validate('Astroset');

        if (!$validate->scene('update')->check($param))
        {
            return show(config('code.error'), (string)$validate->getError());
        }

        $param['uid'] = $this->user['id'];

        if (!(new AstroSettingUser())->updateUserSetting($param))
        {
            return show(config('code.error'), '更新配置失败');
        }

        return show(config('code.success'), '更新配置成功');
    }

    /**
     * 还原星盘配置
     * @method DELETE
     * @return \think\response\Json
     */
    public function restore()
    {
        if (!request()->isPut())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $param = request()->only(['tid', 'chart']);

        $validate = validate('Astroset');

        if (!$validate->scene('delete')->check($param))
        {
            return show(config('code.error'), (string)$validate->getError());
        }

        $param['uid'] = $this->user['id'];

        if (!(new AstroSettingUser())->restoreUserSetting($param))
        {
            return show(config('code.error'), '还原失败');
        }

        return show(config('code.success'), '还原成功');
    }
}
